//
//  HLMineNoteViewController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/9/16.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLMineNoteViewController.h"
#import "HLMineNoteCell.h"
#import "HLUserInfo.h"
#import "HttpRequestManager.h"
#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import "MBProgressHUD+HL.h"
#import "HLMineNote.h"
#import "HLNoteViewController.h"
#import "HLCreateNoteController.h"

#define kPageLimit 10

@interface HLMineNoteViewController ()<UITableViewDelegate,UITableViewDataSource,HLMineNoteCellDelegate>
{
    NSUInteger _currenPage;
}
@property (nonatomic ,strong) UITableView *tableView;
/** 数据源  */
@property (nonatomic ,strong) NSMutableArray *dataSource;

@end

@implementation HLMineNoteViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setUI];
    
    [self setupRefresh];
}

- (void)setUI
{
    self.navigationItem.title = @"我的笔记";
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = HLRGB(245, 245, 245);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight =  60 ;
    [_tableView registerClass:[HLMineNoteCell class] forCellReuseIdentifier:@"HLMineNoteCell"];
    [self.view addSubview:_tableView];
}

- (void)setupRefresh
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUsers)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUsers)];
    
    [self.tableView.mj_header beginRefreshing];
    [self.tableView.mj_header setAutomaticallyChangeAlpha:YES];
    self.tableView.mj_footer.hidden = YES;
}

#pragma mark - Request

- (void)loadNewUsers
{
    [self cancerRequest];
    
    /**** 数据清空 ****/
    [self.dataSource removeAllObjects];
    
    _currenPage = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestGetAllNotes signStr];
    params[@"user_id"] = [HLUserInfo account].userid;
    params[@"page"] = @(_currenPage);
    params[@"limit"] = @(kPageLimit);
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestGetAllNotes parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
        [weakSelf.tableView.mj_header endRefreshing];
        if ([responseObject[@"code"] integerValue] == 200) {
            _currenPage++;
            weakSelf.dataSource = [HLMineNote mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
            [weakSelf.tableView reloadData];
            
            /**** 提示用户数据加载完毕 ****/
            weakSelf.tableView.mj_footer.hidden = NO;
            if (weakSelf.dataSource.count < kPageLimit) {
                _currenPage--;
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                /**** 重置底部状态 ****/
                [weakSelf.tableView.mj_footer endRefreshing];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
    
}

- (void)loadMoreUsers
{
    [self cancerRequest];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestGetAllNotes signStr];
    params[@"user_id"] = [HLUserInfo account].userid;
    params[@"page"] = @(_currenPage);
    params[@"limit"] = @(kPageLimit);
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestGetAllNotes parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
        
        [weakSelf.tableView.mj_footer endRefreshing];
        if ([responseObject[@"code"] integerValue] == 200) {
            _currenPage++;
            NSMutableArray *tempArray = [NSMutableArray array];
            tempArray = [HLMineNote mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [weakSelf.dataSource addObjectsFromArray:tempArray];
          
            [weakSelf.tableView reloadData];
            
            /**** 提示用户数据加载完毕 ****/
            if (tempArray.count < kPageLimit) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [weakSelf.tableView.mj_footer endRefreshing];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
    
}

- (void)requestDeleteMineNote:(HLMineNote *)mineNote
{
    [MBProgressHUD show];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestEditNotes signStr];
    params[@"course_id"] = mineNote.course_id;
    params[@"type"] = @"0";
    params[@"content"] = mineNote.note_content;
    params[@"user_id"] = [HLUserInfo account].userid;
    __weak typeof (self)weakSelf =  self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestEditNotes parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 200) {
            if ([responseObject[@"state"] isEqualToString:@"1"]) {
                [MBProgressHUD showSuccessMessage:@"删除成功"];
                
                /**** 删除某一cell ****/
                [weakSelf.dataSource removeObjectAtIndex:mineNote.cellRow];
                [weakSelf.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:mineNote.cellRow inSection:0]] withRowAnimation:UITableViewRowAnimationRight];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.tableView reloadData];
                });
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HLMineNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HLMineNoteCell"];
    cell.delegate = self;
    HLMineNote *mineNote = self.dataSource[indexPath.row];
    mineNote.cellRow = indexPath.row;
    cell.mineNote = mineNote;
    return cell;
}

#pragma mark - HLMineNoteCellDelegate
- (void)mineNoteCell:(HLMineNoteCell *)mineNoteCell didClickEditMineNote:(HLMineNote *)nimeNote
{
    HLCreateNoteController *createNote = [[HLCreateNoteController alloc] init];
    createNote.title = @"编辑笔记";
    createNote.note_course_id = nimeNote.course_id;
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:createNote];
//    createNote.note = [nimeNote.note_content stringByRemovingPercentEncoding];
    createNote.note = nimeNote.note_content;
    createNote.noteCompletionBlock = ^(NSString *strNote){
        nimeNote.note_content = strNote;
    };
    
    [self presentViewController:nav animated:YES completion:nil];
}

-(void)mineNoteCell:(HLMineNoteCell *)mineNoteCell didClickDeleteMineNote:(HLMineNote *)nimeNote
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示"message:@"真的要删除这条笔记吗?" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"想好了" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        /**** 删除笔记 ****/
        [self requestDeleteMineNote:nimeNote];
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark - Private

- (void)cancerRequest
{
    /**** 取消之前的请求 ****/
    [[HTTPRequestManager defaultManager].sessionManager.tasks makeObjectsPerformSelector:@selector(cancel)];
}

/***** 界面销毁 取消请求 ****/
- (void)dealloc
{
    [self cancerRequest];
}




@end
